<?php
namespace app\admin\controller;
use app\admin\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Cache;

class FileManageController extends AdminBaseController
{
	public function index()
	{

			Cache::clear();

		
		//dump( $list );
		if( Cache::get( 'file_list' ) ){
			$list = Cache::get( 'file_list' );
		}else{
			$list = $this->getFileList( ROOT_PATH.'public/upload' , 'upload' );
			Cache::set( 'file_list' , $list );
		}
		$this->assign( 'list' , $list );
		return $this->fetch();
	}

	private function getExt(){
		return [ 'jpg' , 'jpeg' , 'png' , 'gif' , 'bmp' , 'ico'  ];
	}

	private function getFileList( $dirName , $currentPath )
	{
		$list = [];
		$dir = new \DirectoryIterator( $dirName );
		foreach ($dir as $path => $fileInfo ) {
			if( $fileInfo->getFileName() == '.' || $fileInfo->getFileName() == '..' ){
				continue;
			}
			
			if( $fileInfo->isDir() ){
				$tmp = $this->getFileList( $dirName."/".$fileInfo->getFileName() , $currentPath."/".$fileInfo->getFileName() );
				if( !empty( $tmp ) ){
					$list = array_merge( $list , $tmp );
				}
			}else{
				if( $fileInfo->isFile() && in_array( $fileInfo->getExtension() , self::getExt() ) ){
					$durl = "https://gl.6xq.cn/".$currentPath."/".$fileInfo->getFileName();
					$list [] = [
						'file_path' => $fileInfo->getPathName(),
						'down_path' => $durl,
						'show_img' => '<img style="width:100px;height:100px;" src="'.$durl.'"/>'
					];
				}
			}
		}
		return $list;
	}

	public function todel(){
		$path = $this->request->param( 'path' );
		if( empty( $path ) ){
			return api_json_echo( false , '地址不能为空');
		}
		if( !file_exists( $path ) ){
			return api_json_echo( false , '文件不存在');
		}
		@unlink($path);
		return api_json_echo( false , '删除成功');
	}	
}